//
//  DCAuthPersonalInfoController.m
//  Demo
//
//  Created by zhaolin on 2023/1/9.
//

#import "DCAuthPersonalInfoController.h"
#import "DCAuthInfoCommonCell.h"
#import "DCAuthInfoUIModel.h"
#import "DCAuthFooterView.h"
#import "DCDetailAddressCell.h"
#import "DCAuthPersonalInfoModel.h"
#import "DCPersonalInfoPicker.h"
#import "DCPersonalInfoAddressPicker.h"

@interface DCAuthPersonalInfoController ()<UITableViewDelegate,UITableViewDataSource,DCAuthInfoCommonCellDelegate,DCAuthFooterViewDelegate,DetailAddressCellDelegate>

@property (nonatomic, strong) DCPersonalInfoPicker *pickerView;

@property (nonatomic, strong) DCPersonalInfoAddressPicker *addressPicker;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) NSArray *typeArr;

@property (nonatomic, strong) NSIndexPath *currentIndex;
@end

@implementation DCAuthPersonalInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleName:@"Personal information"];
    // Do any additional setup after loading the view.
}

- (void)configureAlloc {
    [super configureAlloc];
    self.step = @"PERSONAL_INFO";
    self.dataSource = @[].mutableCopy;
    NSArray *titleArr = @[@"Marital Status",@"Number of Children",@"Education Level",
                          @"Working pattern",@"Industry", @"Income Level",
                          @"Pay Period",@"Payday",@"Company name",
                          @"Company phone number(Optional)",@"Altrnative Number(Optional)",@"Home Address",
                          @"Detail Address"];
    
    NSArray *placeholderArr = @[@"",@"",@"",
                                @"",@"",@"",
                                @"",@"",@"Please enter",
                                @"Please enter",@"Please enter",@"",
                                @"Please enter address details"];
    NSArray *cellTypeArr = @[@(DCAuthInfoCommonCellTypeRightDown),@(DCAuthInfoCommonCellTypeRightDown),@(DCAuthInfoCommonCellTypeRightDown),
                             @(DCAuthInfoCommonCellTypeRightDown),@(DCAuthInfoCommonCellTypeRightDown),@(DCAuthInfoCommonCellTypeRightDown),
                             @(DCAuthInfoCommonCellTypeRightDown),@(DCAuthInfoCommonCellTypeRightDown),@(DCAuthInfoCommonCellTypeRightNun),
                             @(DCAuthInfoCommonCellTypeRightNun),@(DCAuthInfoCommonCellTypeRightNun),@(DCAuthInfoCommonCellTypeRightDown),
                             @(DCAuthInfoCommonCellTypeRightNun)];
    NSArray *canEdit = @[@(NO),@(NO),@(NO),
                         @(NO),@(NO),@(NO),
                         @(NO),@(NO),@(YES),
                         @(YES),@(YES),@(NO),
                         @(YES)];
    _typeArr = @[@"MARITAL_STATUS",@"CHILDREN_NUMBER",@"EDUCATION_LEVEL",
                 @"WORKING_PATTERN",@"INDUSTRY",@"INCOME_LEVEL",
                 @"PAY_PERIOD",@"PAY_DAY",@"",
                 @"",@"",@"AREA",
                 @""];
    for (int i = 0; i<titleArr.count; i++) {
        DCAuthInfoUIModel *model = [DCAuthInfoUIModel new];
        model.title = [titleArr objectAtIndex:i];
        model.placeholder = [placeholderArr objectAtIndex:i];
        model.celltype = [[cellTypeArr objectAtIndex:i] intValue];
        model.canEdit = [[canEdit objectAtIndex:i] boolValue];
        [self.dataSource addObject:model];
    }
}
- (void)configureUI {
    [super configureUI];
    [self _setCurrntStep:2];
    [self configureTable];
    [self.tableView registerClass:[DCAuthInfoCommonCell class] forCellReuseIdentifier:NSStringFromClass(DCAuthInfoCommonCell.class)];
    [self.tableView registerClass:[DCDetailAddressCell class] forCellReuseIdentifier:NSStringFromClass(DCDetailAddressCell.class)];
    [self.tableView registerClass:[DCAuthFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass(DCAuthFooterView.class)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topRadiusView.mas_bottom).mas_equalTo(-30);
    }];
    [self.view bringSubviewToFront:self.tableView];
    
    mWeakSelf;
    _pickerView = [[DCPersonalInfoPicker alloc] initWithFrame:CGRectZero];
    _pickerView.cancelCallBack = ^(DCAuthPersonalInfoModel * _Nullable model) {
        [weakSelf pickViewShow:NO];
    };
    _pickerView.sureCallBack = ^(DCAuthPersonalInfoModel * _Nullable model) {
        [weakSelf pickViewShow:NO];
        DCAuthInfoUIModel *uiModel = [weakSelf.dataSource objectAtIndex:weakSelf.currentIndex.row];
        uiModel.personalInfoModel = model;
        uiModel.content = model.remark;
        [weakSelf.tableView reloadData];
    };
    [self.view addSubview:_pickerView];
    [_pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.height);
        make.bottom.mas_equalTo(-self.view.height);
    }];
    
    _addressPicker = [[DCPersonalInfoAddressPicker alloc] initWithFrame:CGRectZero];
    _addressPicker.cancelCallBack = ^(NSString * _Nullable address) {
        [weakSelf addressPickerShow:NO];
    };
    _addressPicker.sureCallBack = ^(NSString * _Nullable address) {
        [weakSelf addressPickerShow:NO];
        DCAuthInfoUIModel *uiModel = [weakSelf.dataSource objectAtIndex:weakSelf.currentIndex.row];
        uiModel.content = address;
        [weakSelf.tableView reloadData];
    };
    [self.view addSubview:_addressPicker];
    [_addressPicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.height);
        make.bottom.mas_equalTo(-self.view.height);
    }];
}

- (void)getDictListWithType:(NSString *)type {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DCHttpRequest DCDictListWithType:type complate:^(NSURLSessionDataTask * _Nonnull operation, DCResponseData * _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (responseObject.code == 200) {
            NSArray *arr = [DCAuthPersonalInfoModel mj_objectArrayWithKeyValuesArray:[responseObject.data objectForKey:@"dictList"]];
            if ([type isEqualToString:@"AREA"]) {
                DCAuthPersonalInfoModel *model = arr.firstObject;
                NSDictionary *dic = [model.typeName mj_JSONObject];
                [self.addressPicker updateDataArr:dic];
                [self addressPickerShow:YES];
            } else {
                [self.pickerView updateDataArr:arr];
                [self pickViewShow:YES];
            }
            
            DLog(@"%@",arr);
        } else {
            [DCDCToast toastText:responseObject.message];
        }
    }];
}
#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DCAuthInfoUIModel *model = [self.dataSource objectAtIndex:indexPath.row];
    if ([model.title isEqualToString:@"Detail Address"]) {
        DCDetailAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(DCDetailAddressCell.class)];
        cell.delegate = self;
        [cell configureDataWithModel:model];
        return cell;
    } else {
        DCAuthInfoCommonCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(DCAuthInfoCommonCell.class)];
        cell.delegate = self;
        [cell configureDataWithModel:model];
        cell.indexPath = indexPath;
        return cell;        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DCAuthInfoUIModel *model = [self.dataSource objectAtIndex:indexPath.row];
    if ([model.title isEqualToString:@"Detail Address"]) {
        return 95;
    } else {
        return 105;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    DCAuthFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass(DCAuthFooterView.class)];
    BOOL contentNull = [self allInfoContentNull];
    [footer setCommitBtnEnabled:!contentNull];
    footer.delegate = self;
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 125;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
#pragma  mark -- DCAuthInfoCommonCellDelegate
- (void)authInfoCommonCellBegainEditingWithText:(NSIndexPath *)index {
    NSString *type = [_typeArr objectAtIndex:index.row];
    if(!type.length) {
        return;
    }
    _currentIndex = index;
    [self getDictListWithType:type];
}

- (BOOL)allInfoContentNull {
    BOOL contentNull= NO;
    for (DCAuthInfoUIModel *model in self.dataSource) {
        
        if ([model.title isEqualToString:@"Home Address"] || [model.title isEqualToString:@"Detail Address"] || [model.title isEqualToString:@"Company name"]) {
            if(!model.content || !model.content.length) {
                contentNull = YES;
//                break;
            }
            DLog(@"%@,%@",model.title,model.content);
        } else if([model.title containsString:@"Optional"]){
            DLog(@"%@,%@",model.title,model.content);
        }else {
            if(!model.personalInfoModel) {
                contentNull = YES;
//                break;
            }
            DLog(@"%@,%@",model.title,model.personalInfoModel);

        }
    }
    return contentNull;
}

- (void)detailAddressCellEndEdting:(NSString *)text {
    [self.tableView reloadData];
}
#pragma mark --- DCAuthFooterViewDelegate
- (void)authFooterViewNextAction:(id _Nullable )sender {
    /*  data: "{
     \"workingPattern\":1, // 工作方式
     \"industry\":1, // 行业
     \"incomeLevel\":1, // 收入水平
     \"province\":\"aaa\", // 一级行政区（州）
     \"area\":\"Aguascalientes\",// 二级行政区
     \"detailedAddress\":\"bbbccc\",// 详细地址
     \"payPeriod\":1, // 付薪周期
     \"companyPhone\":\"1234567\", // 公司电话
     \"altrnativeNumber\":\"7654321\", // 收入水平
     \"corporateName\":\"ddd\", // 公司名称
     \"payday\":\"2\", // 发薪日
     \"maritalStatus\":\"1\", // 婚姻状态
     \"numberOfChildren\":\"1\", // 子女数量
     \"educationQualification\":\"1\", // 教育水平
     }" */
    
    BOOL contentNull = [self allInfoContentNull];
    if(contentNull) {
        return;
    }
    
    NSMutableDictionary *mDic = @{}.mutableCopy;
    DCAuthInfoUIModel *model0 = [self.dataSource objectAtIndex:0];
    [mDic setValue:model0.content forKey:@"maritalStatus"];
    
    DCAuthInfoUIModel *model1 = [self.dataSource objectAtIndex:1];
    [mDic setValue:model1.content forKey:@"numberOfChildren"];

    DCAuthInfoUIModel *model2 = [self.dataSource objectAtIndex:2];
    [mDic setValue:model2.content forKey:@"educationQualification"];
    
    DCAuthInfoUIModel *model3 = [self.dataSource objectAtIndex:3];
    [mDic setValue:model3.content forKey:@"workingPattern"];
    
    DCAuthInfoUIModel *model4 = [self.dataSource objectAtIndex:4];
    [mDic setValue:model4.content forKey:@"industry"];
    
    DCAuthInfoUIModel *model5 = [self.dataSource objectAtIndex:5];
    [mDic setValue:model5.content forKey:@"incomeLevel"];
    
    DCAuthInfoUIModel *model6 = [self.dataSource objectAtIndex:6];
    [mDic setValue:model6.content forKey:@"payPeriod"];
    
    DCAuthInfoUIModel *model7 = [self.dataSource objectAtIndex:7];
    [mDic setValue:model7.content forKey:@"payday"];
    
    DCAuthInfoUIModel *model8 = [self.dataSource objectAtIndex:8];
    [mDic setValue:model8.content forKey:@"corporateName"];
    
    //可选
    DCAuthInfoUIModel *model9 = [self.dataSource objectAtIndex:9];
    if(model9.content && model9.content.length) {
        [mDic setValue:model9.content forKey:@"companyPhone"];
    }
    
    //可选
    DCAuthInfoUIModel *model10 = [self.dataSource objectAtIndex:10];
    if(model10.content && model10.content.length) {
        [mDic setValue:model10.content forKey:@"altrnativeNumber"];
    }
    
    DCAuthInfoUIModel *model11 = [self.dataSource objectAtIndex:11];
    NSArray *arr = [model11.content componentsSeparatedByString:@"   "];
    [mDic setValue:arr.firstObject forKey:@"province"];
    [mDic setValue:arr.lastObject forKey:@"area"];

    DCAuthInfoUIModel *model12 = [self.dataSource objectAtIndex:12];
    [mDic setValue:model12.content forKey:@"detailedAddress"];

    NSString *jsonStr = mDic.mj_JSONString;
    [self saveInfo2:jsonStr];

}

- (void)authFooterViewAgreementAction:(id _Nullable )sender {
    [self pushPrivacyAgreement];
}

- (void)pickViewShow:(BOOL)show {
    [self.pickerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(show?0:self.view.height);
        make.bottom.mas_equalTo(show?0:-self.view.height);
    }];
    self.pickerView.backgroundColor = [[UIColor colorWithString:@"#000000"] colorWithAlphaComponent:0];

    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.pickerView.backgroundColor = [[UIColor colorWithString:@"#000000"] colorWithAlphaComponent:0.7];
    }];
}

- (void)addressPickerShow:(BOOL)show {
    [self.addressPicker mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(show?0:self.view.height);
        make.bottom.mas_equalTo(show?0:-self.view.height);
    }];
    self.addressPicker.backgroundColor = [[UIColor colorWithString:@"#000000"] colorWithAlphaComponent:0];

    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.addressPicker.backgroundColor = [[UIColor colorWithString:@"#000000"] colorWithAlphaComponent:0.7];
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
